/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Gerente.Relatorios;

import Controle.Controlador;
import Modelo.Relatorio;
import java.awt.Color;
import java.text.DateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class RelatorioPedidos extends javax.swing.JFrame {

    DefaultTableModel modelo1;
    TableRowSorter sorter1;
    Relatorio relatorio;
    
    String dataIni;
    String dataFim;

    /**
     * Creates new form Relatorio
     */
//    public RelatorioPizzas() {
//        initComponents();
//    }

    RelatorioPedidos() {
        initComponents();
        this.relatorio = new Relatorio();
        modelo1 = (DefaultTableModel) jtTabela.getModel();
        jScrollPane1. getViewport().setBackground(Color.WHITE);
        jtTabela.getColumnModel().getColumn(1).setPreferredWidth(150);
        dataIni = "01/01/1900";
        dataFim = "01/01/2900";
        //setDadosTela();
        imprimeDadosTabelas();

    }

    public void getDadosVisao() {
        if(validarDadosVisao()){
            relatorio = new Relatorio();
            dataIni = jtDataInicial.getText();
            dataFim = jtDataFinal.getText();
            
            if ("  /  /    ".equals(dataIni)){
                dataIni = "01/01/1900";
            }
            if ("  /  /    ".equals(dataFim)){
                dataFim = "01/01/2900";
            }
        }
    }

    public boolean dataValida(String data) {
        try {
            if ("  /  /    ".equals(data)) {
                return true;
            }
            Date d = DateFormat.getDateInstance().parse(data);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public boolean validarDadosVisao() {
        try {
//            Matcher Lestras = Pattern.compile("[a-zA-Z]").matcher(jTnumeroBuscaDS.getText());
            Matcher Numeros;// = Pattern.compile("[0-9]").matcher();

            // validar a data inicial 
            if (!dataValida(jtDataInicial.getText())) {
                throw new Exception("Erro: Formato Inválido!\nA Data Inicial do Relatório é Inválida\nPreencha o campo no formato: dd/mm/aaaa");
            }
            // validar a data Final 
            if (!dataValida(jtDataFinal.getText())) {
                throw new Exception("Erro: Formato Inválido!\nA Data Final do Relatório é Inválida\nPreencha o campo no formato: dd/mm/aaaa");
            }
            return true;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Erro!", 0);
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jtDataInicial = new javax.swing.JFormattedTextField();
        jtDataFinal = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtTabela = new javax.swing.JTable();
        jbPesquisar = new javax.swing.JButton();
        jbGerarPDF = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jtTotalPedidos = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtValorTotalPedidos = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jtValorMedioPedidos = new javax.swing.JTextField();
        jbItensPedido = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RELATÓRIOS");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Relatório dos Sabores Mais Vendidos");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED, java.awt.Color.gray, java.awt.Color.darkGray));
        jPanel1.setPreferredSize(new java.awt.Dimension(652, 77));

        jLabel4.setText("Periodo:");

        try {
            jtDataInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtDataInicial.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtDataInicial.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtDataInicial.setPreferredSize(new java.awt.Dimension(100, 20));

        try {
            jtDataFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtDataFinal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtDataFinal.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtDataFinal.setPreferredSize(new java.awt.Dimension(100, 20));

        jLabel7.setText("de");

        jLabel8.setText("até");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(122, 122, 122)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44)
                .addComponent(jLabel8)
                .addGap(43, 43, 43)
                .addComponent(jtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtDataInicial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(jtDataFinal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jtTabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nome", "Data", "Tx Entrega", "Desconto", "Vlr Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtTabela);

        jbPesquisar.setText("Pesquisar");
        jbPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPesquisarActionPerformed(evt);
            }
        });

        jbGerarPDF.setText("Gerar PDF");
        jbGerarPDF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbGerarPDFActionPerformed(evt);
            }
        });

        jLabel2.setText("Total de Pedidos:");

        jtTotalPedidos.setEditable(false);
        jtTotalPedidos.setPreferredSize(new java.awt.Dimension(80, 20));

        jLabel3.setText("Valor Total Pedidos:");

        jtValorTotalPedidos.setEditable(false);
        jtValorTotalPedidos.setPreferredSize(new java.awt.Dimension(120, 20));

        jLabel5.setText("Valor Médio do Pedidos");

        jtValorMedioPedidos.setEditable(false);
        jtValorMedioPedidos.setPreferredSize(new java.awt.Dimension(120, 20));

        jbItensPedido.setText("<html><Center>Itens<br>Pedido");
        jbItensPedido.setToolTipText("");
        jbItensPedido.setPreferredSize(new java.awt.Dimension(81, 23));
        jbItensPedido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbItensPedidoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtTotalPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtValorMedioPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtValorTotalPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 697, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbPesquisar)
                            .addComponent(jbGerarPDF)
                            .addComponent(jbItensPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(50, 50, 50)
                        .addComponent(jbGerarPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(jbItensPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 211, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtValorTotalPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5)
                    .addComponent(jtValorMedioPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jtTotalPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-824)/2, (screenSize.height-559)/2, 824, 559);
    }// </editor-fold>//GEN-END:initComponents

    private void jbGerarPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbGerarPDFActionPerformed
        // TODO add your handling code here:
        gerarPDF();
    }//GEN-LAST:event_jbGerarPDFActionPerformed

    private void jbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPesquisarActionPerformed
        // TODO add your handling code here:
        if (validarDadosVisao()) {
            getDadosVisao();
            novaPesquisa();
        }
    }//GEN-LAST:event_jbPesquisarActionPerformed

    private void jbItensPedidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbItensPedidoActionPerformed
        // TODO add your handling code here:
        try {
            int linha = jtTabela.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt(jtTabela.getValueAt(linha, 0).toString());
                Controlador.gerarPdfRelatorioItensPedido(codigo);
                
            } else {
                throw new Exception("Selecione a linha do Sabor desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jbItensPedidoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbGerarPDF;
    private javax.swing.JButton jbItensPedido;
    private javax.swing.JButton jbPesquisar;
    private javax.swing.JFormattedTextField jtDataFinal;
    private javax.swing.JFormattedTextField jtDataInicial;
    private javax.swing.JTable jtTabela;
    private javax.swing.JTextField jtTotalPedidos;
    private javax.swing.JTextField jtValorMedioPedidos;
    private javax.swing.JTextField jtValorTotalPedidos;
    // End of variables declaration//GEN-END:variables

    private boolean getDadosAcomp() {
        try {
            relatorio = Controlador.carregarDadosBD_RelPedidos(dataIni, dataFim) ;
            if (relatorio != null) {
                return true;
            } else {
                throw new Exception("não foi encontrada nenhuma referencia aos dados de Busca.\nTente novamente!");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,e.getMessage() , "Erro!", 0);
            return false;
        }
    }

    private boolean imprimeDadosTabelas() {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela1 = 0;
        getDadosAcomp();
        if (relatorio == null) {
            return false;
        }
        for (int i = 0; i < relatorio.getRelPedidos().size(); i++) {

            if (jtTabela.getRowCount() <= linhaTabela1) {
                modelo1.addRow(new String[]{"", ""});
            }
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getCodigo(), linhaTabela1, 0);
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getNome(), linhaTabela1, 1);
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getData(), linhaTabela1, 2);
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getValor_entrega(), linhaTabela1, 3);
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getDesconto(), linhaTabela1, 4);
            jtTabela.setValueAt(relatorio.getRelPedidos().get(i).getValor_total(), linhaTabela1, 5);
            
            if(i==0){
                jtTotalPedidos.setText(relatorio.getRelPedidos().get(i).getNum_pedidos());
                jtValorMedioPedidos.setText(relatorio.getRelPedidos().get(i).getValor_medio_pedidos());
                jtValorTotalPedidos.setText(relatorio.getRelPedidos().get(i).getValor_total_pedidos());
            }
            linhaTabela1++;
        }
        removeLinhasInutilizadas(linhaTabela1);
        return true;
    }

    public void removeLinhasInutilizadas(int inicioTab1) {
        for (int i = inicioTab1; i < jtTabela.getRowCount(); i++) {
            modelo1.removeRow(i);
        }
    }

    public void LimparTabela() {
        while (jtTabela.getRowCount() > 0) {
            modelo1.removeRow(0);
        }
    }

    public void novaPesquisa() {
        LimparTabela();
        imprimeDadosTabelas();
    }

    public void gerarPDF() {

    }
}
